import { ref } from 'vue';
import { defineStore } from 'pinia';
import type { Rule } from '../types';
import { apiClient } from '../api/client';

export const useRulesStore = defineStore('rules', () => {
  // 状态
  const rules = ref<Rule[]>([]);
  const loading = ref(false);
  const error = ref<string | null>(null);

  // 获取规则列表
  async function fetchRules() {
    try {
      console.log('🔄 开始获取规则列表...');
      loading.value = true;
      error.value = null;
      
      const response = await apiClient.getRules();
      console.log('📋 API响应:', response);
      console.log('📋 规则数据:', response.data);
      
      rules.value = response.data;
      console.log('📋 Store中的规则数量:', rules.value.length);
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取规则失败';
      console.error('❌ 获取规则失败:', err);
    } finally {
      loading.value = false;
    }
  }

  // 创建规则
  async function createRule(rule: Omit<Rule, 'id' | 'createdAt' | 'updatedAt'>) {
    try {
      const response = await apiClient.createRule(rule);
      rules.value.unshift(response.data);
      return response.data;
    } catch (err) {
      console.error('创建规则失败:', err);
      throw err;
    }
  }

  // 更新规则
  async function updateRule(id: string, rule: Partial<Rule>) {
    try {
      const response = await apiClient.updateRule(id, rule);
      const index = rules.value.findIndex(r => r.id === id);
      if (index >= 0) {
        rules.value[index] = response.data;
      }
      return response.data;
    } catch (err) {
      console.error('更新规则失败:', err);
      throw err;
    }
  }

  // 删除规则
  async function deleteRule(id: string) {
    try {
      await apiClient.deleteRule(id);
      const index = rules.value.findIndex(r => r.id === id);
      if (index >= 0) {
        rules.value.splice(index, 1);
      }
    } catch (err) {
      console.error('删除规则失败:', err);
      throw err;
    }
  }

  // 切换规则启用状态
  async function toggleRule(id: string) {
    const rule = rules.value.find(r => r.id === id);
    if (rule) {
      await updateRule(id, { enabled: !rule.enabled });
    }
  }

  // 测试规则
  async function testRule(rule: Rule, transactionId: string) {
    try {
      const response = await apiClient.testRule(rule, transactionId);
      return response.data.matched;
    } catch (err) {
      console.error('测试规则失败:', err);
      throw err;
    }
  }

  // 获取启用的规则
  function getEnabledRules() {
    return rules.value.filter(rule => rule.enabled);
  }

  // 获取禁用的规则
  function getDisabledRules() {
    return rules.value.filter(rule => !rule.enabled);
  }

  return {
    // 状态
    rules,
    loading,
    error,
    
    // 方法
    fetchRules,
    createRule,
    updateRule,
    deleteRule,
    toggleRule,
    testRule,
    getEnabledRules,
    getDisabledRules
  };
}); 